package com.pingancar.creditmanage.service;

import com.pingancar.creditmanage.dao.FeedbackDaoImpl;
import com.pingancar.creditmanage.dao.InsuranceDaoImpl;
import com.pingancar.creditmanage.dao.PAServiceDaoImpl;
import com.pingancar.creditmanage.dao.UserDaoImpl;
import com.pingancar.creditmanage.pojo.FeedbackPojo;
import com.pingancar.creditmanage.pojo.InsurancePojo;
import com.pingancar.creditmanage.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2014/9/6 0006.
 */
@Service
public class UserServiceImpl {
    @Autowired
    UserDaoImpl userDao;
    @Autowired
    PAServiceDaoImpl paServiceDao;
    @Autowired
    InsuranceDaoImpl insuranceDao;
    @Autowired
    FeedbackDaoImpl feedbackDao;

    public boolean registerUser(String mobilephone, String password, String carno, String name) {
        UserPojo userPojo = new UserPojo();
        userPojo.setPasswd(password);
        userPojo.setMobilephone(mobilephone);
        if(!checkUser(userPojo)){
            return false;
        }

        List<UserPojo> userlist = userDao.findByProperty("mobilephone", mobilephone);
        if (userlist != null && !userlist.isEmpty())
            return false;

        //未填写车牌号的情况
        if (carno == null || carno == "") {
            userPojo.setCredit(0);
            userPojo.setRegtime(new Timestamp(new Date().getTime()));
            userDao.save(userPojo);
            return true;
        }

        //填写车牌号的情况
        if (name == null || name == "")
            return false;
        List<InsurancePojo> inslist = insuranceDao.findByProperty("carno", carno);
        if (inslist == null || inslist.isEmpty())
            return false;

        int credit = 0;
        long curr = new Date().getTime();
        boolean hasInsure = false;      //标记名下是否有保险

        for (InsurancePojo i : inslist) {
            if (i.getUser() != null || !i.getName().equals(name))
                continue;

            hasInsure = true;
            if (i.getStarttime().getTime() <= curr && i.getEndtime().getTime() >= curr)
                credit += i.getCredit();
        }

        if (!hasInsure)
            return false;

        userPojo.setCredit(credit);
        userPojo.setUsername(name);
        userPojo.setRegtime(new Timestamp(new Date().getTime()));
        userDao.save(userPojo);

        for (InsurancePojo i : inslist) {
            if (i.getUser() != null || !i.getName().equals(name))
                continue;

            i.setUser(userPojo);
            insuranceDao.update(i);
        }

        return true;
    }

    public UserPojo login(UserPojo userPojo) {
        if (!checkUser(userPojo))
            return null;
        List<UserPojo> result= userDao.findByProperty("mobilephone", userPojo.getMobilephone());
        if(result == null || result.isEmpty()){
            return null;
        }

        UserPojo u = result.get(0);
        if (u.getPasswd().equals(userPojo.getPasswd()))
            return u;

        return null;
    }

    private boolean checkUser(UserPojo userPojo){
        //密码不能小于6位
        if(userPojo.getPasswd().length()<6){
            return false;
        }
        //用户名不能小于4位
//        if(userPojo.getUsername().length()<4){
//            return false;
//        }
        //检验是否存在非法字符

        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        if(p.matcher(userPojo.getPasswd()).find()){
            return false;
        }

        return true;
    }

    /**
     * 添加车牌
     * @param userPojo
     * @param carno
     * @return
     */
    public UserPojo addCarNo(UserPojo userPojo, String carno) {
        if (userPojo == null || userPojo.getUsername() == null || userPojo.getUsername() == "")
            return null;

        List<InsurancePojo> l = insuranceDao.findByProperty("carno", carno);
        if (l == null || l.isEmpty())
            return null;

        int credit = userPojo.getCredit();

        long curr = new Date().getTime();
        for (InsurancePojo i : l) {
            if (i.getUser() != null)
                continue;

            if (!i.getName().equals(userPojo.getUsername()))
                continue;

            /* 判断保单是否已生效 */
            if (i.getStarttime().getTime() <= curr && i.getEndtime().getTime() >= curr)
                credit += i.getCredit();

            i.setUser(userPojo);
            insuranceDao.update(i);
        }

        userPojo.setCredit(credit);
        userDao.update(userPojo);

        return userPojo;
    }

    public List<InsurancePojo> getInsuranceList(Integer uid) {
        return insuranceDao.findByProperty("user.id", uid);
    }

    public UserPojo modifyPw(UserPojo userPojo, String oldpw, String newpw) {
        if (userPojo == null)
            return null;

        if (!userPojo.getPasswd().equals(oldpw))
            return null;

        userPojo.setPasswd(newpw);
        userDao.update(userPojo);
        return userPojo;
    }

    public boolean addFeedback(UserPojo userPojo, FeedbackPojo feedbackPojo) {
        if (userPojo == null || feedbackPojo == null)
            return false;

        feedbackPojo.setTime(new Timestamp(new Date().getTime()));
        feedbackPojo.setUser(userPojo);
        feedbackDao.save(feedbackPojo);

        return true;
    }
}
